package com.sgb.packers.view.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.link.router.PathTeam;
import com.sgb.net.entity.ListResponse;
import com.sgb.packers.R;
import com.sgb.packers.databinding.PackersActivityProjectBinding;
import com.sgb.packers.databinding.PackersDialogSendBinding;
import com.sgb.packers.entity.ProjectEntity;
import com.sgb.packers.view.adapter.ProjectListAdapter;
import com.sgb.packers.viewmodel.ProjectListViewModel;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.interfaces.DialogClick;
import com.swgk.core.util.MToast;
import com.swgk.core.util.MapUtils;
import com.swgk.core.util.NewDialogHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * @author 王彬臣
 * @date 2021/11/25
 * @Description 项目管理
 */
@Route(path = PathTeam.ProjectManagerActivity)
public class ProjectManagerActivity extends BaseActivity<ProjectListViewModel, PackersActivityProjectBinding> {
    private ProjectListAdapter mAdapter;
    private int projectPos;
    private String projectNo;
    private PackersDialogSendBinding mSendBinding;
    private CountDownTimer mTimer;
    private final List<ProjectEntity> mList = new ArrayList<>();
    private RoundCornerDialog dialog;
    private boolean isCreateNew;

    @Autowired(name = "position", desc = "项目名称")
    int position;

    @Override
    protected int layoutId() {
        return R.layout.packers_activity_project;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(ProjectListViewModel.class);
    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        mBinding.actionBar.setOnBackClickListener(this);
        mBinding.actionBar.setMenuFunctionClick(this);
        mAdapter = new ProjectListAdapter(mList);
        mBinding.rvList.setLayoutManager(new LinearLayoutManager(this));
        DividerDecoration.builder(this)
                .color(ContextCompat.getColor(this, R.color.color_f5f5f5))
                .size(5, TypedValue.COMPLEX_UNIT_DIP)
                .build()
                .addTo(mBinding.rvList);
        mAdapter.bindToRecyclerView(mBinding.rvList);
        mAdapter.setEmptyView(R.layout.packers_empty_views);
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.tv_edit) {
                ProjectEntity entity = mList.get(position);
                RoundCornerDialog newDialogHelper = new NewDialogHelper<String>(ProjectManagerActivity.this)
                        .editDialog(false, true, "编辑项目名称", "请输入项目名称", "确定", "取消", entity.getProjectName())
                        .setDialogClick(new DialogClick<String>() {
                            @Override
                            public void confirmClick(String s, Dialog dialog) {
                                if (TextUtils.isEmpty(s)){
                                    MToast.showToast(ProjectManagerActivity.this,"请输入项目名称");
                                    return;
                                }
                                mViewModel.addProject(new MapUtils().pair2Map(Pair.create("no", entity.getNo()), Pair.create("projectName", s), Pair.create("type", 1)));
                                dialog.cancel();
                            }
                        })
                        .build();
                newDialogHelper.show();
            } else if (view.getId() == R.id.tv_del) {
                projectPos = position;
                projectNo = mList.get(position).getNo();
                new RoundDialog.Builder(ProjectManagerActivity.this)
                        .title("温馨提示")
                        .content("确认删除？")
                        .cancel("取消")
                        .confirm("确定")
                        .cancelable(false)
                        .confirmCallback(v12 -> sendCodeDialog())
                        .show();
            }
        });

        mBinding.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mViewModel.getProject(true, new MapUtils().pair2Map(Pair.create("type", 1)));
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mViewModel.getProject(false, new MapUtils().pair2Map(Pair.create("type", 1)));
            }
        });
        initData();

    }

    public void sendCodeDialog() {
        View view = View.inflate(this, R.layout.packers_dialog_send, null);
        mSendBinding = DataBindingUtil.bind(view);
        dialog = new RoundCornerDialog(this, 0, 0, view, R.style.RoundCornerDialog);
        dialog.show();
        dialog.setCanceledOnTouchOutside(false);
        mSendBinding.tvLogoutCancel.setOnClickListener(v -> dialog.dismiss());
        mSendBinding.tvLogoutConfirm.setOnClickListener(v -> {
            String code = mSendBinding.ediInput.getText().toString();
            if (!TextUtils.isEmpty(code)) {
                mViewModel.delProject(projectNo, code);
            } else {
                MToast.showToast(ProjectManagerActivity.this, "验证码不能为空");
            }
        });
        mSendBinding.tvSend.setOnClickListener(v -> {
            mSendBinding.tvSend.setEnabled(false);
            mViewModel.sendCode();
        });
    }

    public void countTime() {
        mTimer = new CountDownTimer(60 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                if (!isFinishing()) {
                    mSendBinding.tvSend.setText(String.format(Locale.CHINA,"%d秒后重新获取",millisUntilFinished / 1000));
                    mSendBinding.tvSend.setTextColor(getResources().getColor(R.color.color_666666));
                }
            }

            @Override
            public void onFinish() {
                if (!isFinishing()) {
                    mSendBinding.tvSend.setEnabled(true);
                    mSendBinding.tvSend.setText("获取验证码");
                    mSendBinding.tvSend.setTextColor(getResources().getColor(R.color.color_5792FD));
                }
            }
        };
        mTimer.start();
    }

    private void initData() {
        mViewModel.getProject(false, new MapUtils().pair2Map(Pair.create("type", 1)));
        mViewModel.mAddProjectLiveData.observe(this, suc -> {
            if (suc) {
                isCreateNew = true;
                mViewModel.getProject(false, new MapUtils().pair2Map(Pair.create("type", 1)));
            }
        });
        mViewModel.mGetProjectLiveData.observe(this, this::syncData);
        mViewModel.mDelProject.observe(this, suc -> {
            if (mList.get(position).getNo().equals(projectNo)){
                isCreateNew = true;
            }
            mList.remove(projectPos);
            mAdapter.notifyDataSetChanged();
            dialog.dismiss();
        });
        mViewModel.mCodeResult.observe(this, suc -> countTime());
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == com.sgb.link.R.id.iv_back_red) {
            if (mList != null && mList.size() > 0){
                Intent intent = new Intent();
                if (isCreateNew){
                    intent.putExtra("name",mList.get(0).getProjectName() + "---");
                }else {
                    intent.putExtra("name", mList.get(position).getProjectName());
                }
                setResult(2,intent);
            }else {
                Intent intent = new Intent();
                intent.putExtra("name","没有项目");
                setResult(2,intent);
            }
            finish();
        } else if (v.getId() == com.sgb.link.R.id.right_view_red) {
            RoundCornerDialog newDialogHelper = new NewDialogHelper<String>(this)
                    .editDialog(false, true, "新建项目", "请输入项目名称", "确定", "取消")
                    .setDialogClick(new DialogClick<String>() {
                        @Override
                        public void confirmClick(String s, Dialog dialog) {
                            if (TextUtils.isEmpty(s)){
                                MToast.showToast(ProjectManagerActivity.this,"请输入项目名称");
                                return;
                            }
                            mViewModel.addProject(new MapUtils().pair2Map(Pair.create("projectName", s), Pair.create("type", 1)));
                            dialog.cancel();
                        }
                    })
                    .build();
            newDialogHelper.show();
        }
    }

    public void syncData(ListResponse<List<ProjectEntity>> entity) {
        mBinding.refreshLayout.finishRefresh();
        mBinding.refreshLayout.finishLoadMore();
        if (mViewModel.pageNum == 1) {
            mList.clear();
        }
        if (entity.getList() != null) {
            mList.addAll(entity.getList());
        }
        mAdapter.notifyDataSetChanged();
        if (entity.getCurrentPage() < entity.getTotalPage()) {
            mBinding.refreshLayout.resetNoMoreData();
        } else {
            mBinding.refreshLayout.finishLoadMoreWithNoMoreData();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    @Override
    public void onBackPressedSupport() {
        if (mList != null && mList.size() > 0){
            Intent intent = new Intent();
            if (isCreateNew){
                intent.putExtra("name",mList.get(0).getProjectName() + "---");
            }else {
                intent.putExtra("name", mList.get(position).getProjectName());
            }
            setResult(2,intent);
        }else {
            Intent intent = new Intent();
            intent.putExtra("name","没有项目");
            setResult(2,intent);
        }
        super.onBackPressedSupport();
    }
}
